<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { statisticsAgeInfo } from '@/api/charts.js'
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      ageInfo: [
        { le0: '不限' },
        { le18: '18以下' },
        { le25: '25以下' },
        { le30: '30以下' },
        { le35: '35以下' },
        { le40: '40以下' },
        { le45: '45以下' },
        { le50: '50以下' },
        { le55: '55以下' },
        { le60: '60以下' },
        { le65: '65以下' }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {})
    statisticsAgeInfo().then(response => {
      const yaxisData = []
      const xaxisData = []
      this.ageInfo.forEach(item => {
        xaxisData.push(item[Object.keys(item)[0]])
        yaxisData.push(response.result[Object.keys(item)[0]])
      })
      this.initChart(xaxisData, yaxisData)
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(xaxisData, yaxisData) {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
          position: function(p) {
            return [p[0] + 10, p[1] - 10]
          },
          extraCssText: 'width:80px;height:54px'
        },
        grid: {
          top: 30,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xaxisData,
            axisLabel: {
              interval: 0,
              rotate: 40
            }
          }
        ],
        yAxis: {
          type: 'value',
          name: '单位/人'
        },
        series: [
          {
            data: yaxisData,
            type: 'bar',
            barWidth: '60%',
            barCategoryGap: 50
          }
        ]
      })
    }
  }
}
</script>
